import http from "../utils/request.js";

const paging = {
    total: 9,
    pageNum: 1,
    pages: 3,
    pageSize: 3
}

function renderStudents(arr) {
    $("#studentsTb").html();
    let content = arr.map(item => {
        return `<tr>
          <td>${item._id}</td>
          <td>${item.name}</td>
          <td>${item.age}</td>
          <td>${item.sex}</td>
          <td>${item.classId.name}</td>
          <td>  <img width="20px" src="http://127.0.0.1:3000/${item.imgSrc}" alt="">  </td>
          <td>${item.classId.tid.name}</td>
          <td> <button>修改</button>
          <button>删除</button></td>
          </tr>`
    })
    $("#studentsTb").html(content);
    $(".pageNum1").html(paging.pageSize);
    $(".pageNum2").html(paging.total);
    $(".pageNum3").html(paging.pageNum);
    $(".pageNum4").html(paging.pages);
}

async function getAllStudents() {
    let {
        code,
        students,
        total,
        pages
    } = await http({ url: "/api/students/pageStudents", type: "post", data: { pageNum: paging.pageNum, pageSize: paging.pageSize } });
    paging.pages = pages;
    paging.total = students.length;
    // console.log( students);
    renderStudents(students);
}

getAllStudents();

//查询
$("body").on("blur", ".searchStudent", async function () {
    let key = $("#searchInput").val();
    let value = $(this).val();
    console.log(key, value);
    let { students } = await http({ url: "/api/students/searchStudents", type: "post", data: { key, value } })
    paging.total = students.length;
    paging.pageNum = 1;
    paging.pages = 1;
    renderStudents(students);
})

//分页
$("body").on("click", "#userPage", async function () {
    paging.pageNum = 1;
    paging.pageSize = $(this).val();
    getAllStudents();
})

$("body").on("click", ".prevBtn", async function () {
    if (paging.pageNum > 1) {
        paging.pageNum--;
        getAllStudents();
    }


})
$("body").on("click", ".nextBtn", async function () {

    if (paging.pageNum < paging.pages) {
        paging.pageNum++;
        getAllStudents();
    }

})


//动态渲染班级（添加学生）
async function getAllClasses() {
    const { classes } = await http({ url: "/api/classes", type: "get" });
    let str = classes.map(item => {
        return `<option value=${item._id}>${item.name}</option>`
    });
    $("#selectClasses").html(str);
    // console.log(classes);
}
getAllClasses();

//文件上传
$("body").on("change", "#fileImg", async function (e) {
    const files = $(e.target.files);
    console.log(files);
    const fd = new FormData();
    fd.append("file", files[0]);
    $.ajax({
        url: "/api/upload/image",
        type: "POST",
        data: fd,
        contentType: false,
        processData: false,
        cache: false,
        success(res) {
            console.log("文件上传成功", res);
            $("#showImg").attr("src", `http://127.0.0.1:3000/temp/${res.data || "../assets/default.jpeg"}`);
            $("#showImg").attr("data", `${res.data}`);
        }
    })
})
//添加
$("body").on("click", "#addStudentsBtn", async function () {
    let name = $("#addStudentsName").val();
    let age = $("#addStudentsAge").val();
    let sex = $("[name='addStudentsGender']:checked ").val();
    let classId = $("#selectClasses").val();
    let imgSrc = $("#showImg").attr("data");

    // console.log(name,age,sex,classId,imgSrc);
    const { code } = await http({ url: "/api/upload/addImage", type: "post", data: {imgSrc } });
    if(code){
       const { message } = await http({ url: "/api/students", type: "post", data: { name, age, sex, classId, imgSrc } });
        alert(message);
    }
    
})

//删除图片
$("body").on("click", "#dele", async function () {

    let imgSrc = $("#showImg").attr("data");
    console.log(imgSrc);
   const {code} =await http({ url: "/api/upload/del", type: "post", data: { imgSrc } });
   console.log(code);
   if(code){
$("#showImg").attr("src","http://127.0.0.1:3000/assets/default.jpeg");
   }else{
       alert("删除失败")
   }
    
    console.log(message);
})